package cn.edu.zafu.bigdata.Yum;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class AppendAndReadFile {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入文本
        System.out.println("请输入要追加的文本：");
        String content = scanner.nextLine();

        // 文件名，这里以学号为例
        String fileName = "files/202211080112.txt";

        // 追加内容到文件
        appendToFile(fileName, content);

        // 读取文件并显示内容
        readFile(fileName);

        scanner.close();
    }


    public static void appendToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) { // true 表示追加内容
            writer.write(content);
            writer.newLine(); // 添加换行符，以便下次追加时内容不会连在一起
            System.out.println("文本已成功追加到文件：" + fileName);
        } catch (IOException e) {
            System.err.println("追加内容到文件时发生错误：" + e.getMessage());
        }
    }


    public static void readFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            System.out.println("文件内容如下：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}
